package cn.xfdzx.android.apps.shop.fragment.car;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.xfdzx.android.apps.shop.R;
import cn.xfdzx.android.apps.shop.activity.XFDConfirmOrderActivity;
import cn.xfdzx.android.apps.shop.activity.XFDGoodsDeatailsActivity;
import cn.xfdzx.android.apps.shop.activity.login.OneLoginMainActivity;
import cn.xfdzx.android.apps.shop.adapter.CarWholesaleAdapter;
import cn.xfdzx.android.apps.shop.apps.Constants;
import cn.xfdzx.android.apps.shop.base.BaseMvpFragment;
import cn.xfdzx.android.apps.shop.bean.BaseObjectBean;
import cn.xfdzx.android.apps.shop.bean.ConfirmGoodBeen;
import cn.xfdzx.android.apps.shop.bean.ShopCarListBeen;
import cn.xfdzx.android.apps.shop.contract.ItemClickListener;
import cn.xfdzx.android.apps.shop.contract.ShopCarListContract;
import cn.xfdzx.android.apps.shop.evenbus.CarInitDataMessage;
import cn.xfdzx.android.apps.shop.evenbus.HomeFlushCarData;
import cn.xfdzx.android.apps.shop.evenbus.PostCarNumMessage;
import cn.xfdzx.android.apps.shop.evenbus.UpdateCarNumMessage;
import cn.xfdzx.android.apps.shop.fragment.OneFragment;
import cn.xfdzx.android.apps.shop.presenter.ShopCarListPresenter;
import cn.xfdzx.android.apps.shop.util.ProgressDialog;
import cn.xfdzx.android.apps.shop.util.Utils;
import cn.xfdzx.android.apps.shop.util.UtilsData;

import static cn.xfdzx.android.apps.shop.activity.MainActivity.TYPE_IS_RETAIL;
import static cn.xfdzx.android.apps.shop.apps.Constants.APP_TOKEN;

/**
 * @author gzk
 * @date 2020/3/26 0026
 * description：购物车批发
 */
public class CarMarketPurchaseFragment extends BaseMvpFragment<ShopCarListPresenter> implements ShopCarListContract.View {


    RecyclerView rvMarket;
    TextView tvAllSelect;
    TextView tvTotalMonry;
    TextView tvSettlement;//结算


    private CarWholesaleAdapter carWholesaleAdapter;

    private List<ShopCarListBeen.DataBean.ValidBean> mList;
    private int index;
    private Dialog dialog;
    private LinearLayout llCarEmpty;//购物车为空
    private RelativeLayout rlBottom;

    @Override
    protected void initView(View view) {
        rvMarket = view.findViewById(R.id.rv_market);
        tvAllSelect = view.findViewById(R.id.tv_all_select);
        tvTotalMonry = view.findViewById(R.id.tv_total_monry);
        tvSettlement = view.findViewById(R.id.tv_settlement);
        llCarEmpty = view.findViewById(R.id.ll_car_empty);
        rlBottom = view.findViewById(R.id.rl_bottom);

        EventBus.getDefault().register(this);
        mPresenter = new ShopCarListPresenter();
        mPresenter.attachView(this);
        mList = new ArrayList<>();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvMarket.setLayoutManager(linearLayoutManager);
        rvMarket.setItemAnimator(new DefaultItemAnimator());
        rvMarket.setFocusableInTouchMode(false);
        carWholesaleAdapter = new CarWholesaleAdapter(getContext(), mList, mPresenter);
        carWholesaleAdapter.setOnItemClickListener(new ItemClickListener() {
            @Override
            public void onItemClick(int position) {

            }
        });
        rvMarket.setAdapter(carWholesaleAdapter);

//        mPresenter.initData("1");
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void XXX(CarInitDataMessage messageEvent) {
        if (messageEvent.getMessage() == 1) {
            tvTotalMonry.setText("¥0.0");
            Drawable nav_up = getResources().getDrawable(R.drawable.d99999_oval);
            nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
            tvAllSelect.setCompoundDrawables(nav_up, null, null, null);

            mPresenter.initData("1");
        }
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_car_market_purchase;
    }

    @Override
    public void showLoading() {
        if (TYPE_IS_RETAIL == 1) {
            if (!ProgressDialog.getInstance().materialDialog.isShowing()) {
                ProgressDialog.getInstance().show(getActivity());
            }
        }
    }

    @Override
    public void hideLoading() {
        if (TYPE_IS_RETAIL == 1) {
            ProgressDialog.getInstance().dismiss();
        }
    }


    @Override
    public void onError(Throwable throwable) {
        Toast.makeText(getActivity(), "网络请求出错", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onInitSuccess(ShopCarListBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            index = bean.getData().getValid().size();
            mList.clear();
            mList.addAll(bean.getData().getValid());
            for (ShopCarListBeen.DataBean.ValidBean validBean : bean.getData().getInvalid()) {
                validBean.setIs_select(true);
                for (ShopCarListBeen.DataBean.ValidBean.GoodsBeanX goodsBeanX : validBean.getGoods()) {
                    goodsBeanX.setIs_select(true);
                }
            }
            if (bean.getData().getInvalid().size() != 0) {
                for (int i = 1; i < bean.getData().getInvalid().size(); i++) {
                    bean.getData().getInvalid().get(0).getGoods().addAll(bean.getData().getInvalid().get(i).getGoods());
                }


                mList.add(bean.getData().getInvalid().get(0));
            }
            carWholesaleAdapter.setIndex(index, tvAllSelect, tvTotalMonry);
            carWholesaleAdapter.notifyDataSetChanged();
            tvAllSelect.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    {
                        double total_money = 0;
                        boolean is_all = true;
                        for (int i = 0; i < index; i++) {
                            for (ShopCarListBeen.DataBean.ValidBean.GoodsBeanX goodsBeanX : mList.get(i).getGoods()) {
                                if (goodsBeanX.isIs_select()) {
                                } else {
                                    is_all = false;
                                    break;
                                }
                            }
                            if (!is_all) {
                                break;
                            }
                        }
                        if (is_all) {
                            for (int i = 0; i < index; i++) {
                                for (ShopCarListBeen.DataBean.ValidBean.GoodsBeanX goodsBeanX : mList.get(i).getGoods()) {
                                    goodsBeanX.setIs_select(false);
                                }
                            }
                            total_money = 0.0;
                            Drawable nav_up = getResources().getDrawable(R.drawable.d99999_oval);
                            nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
                            tvAllSelect.setCompoundDrawables(nav_up, null, null, null);
                        } else {
                            for (int i = 0; i < index; i++) {
                                for (ShopCarListBeen.DataBean.ValidBean.GoodsBeanX goodsBeanX : mList.get(i).getGoods()) {
                                    goodsBeanX.setIs_select(true);
                                    total_money = Utils.addDouble(total_money, Utils.mul(Double.parseDouble(goodsBeanX.getProductInfo().getPrice()), goodsBeanX.getCart_num()));
                                }
                            }
                            Drawable nav_up = getResources().getDrawable(R.drawable.icon_green_dui);
                            nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
                            tvAllSelect.setCompoundDrawables(nav_up, null, null, null);
                        }
                        carWholesaleAdapter.notifyDataSetChanged();
                        tvTotalMonry.setText("¥" + total_money);
                    }
                }
            });
            tvSettlement.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Utils.isFastClick()) {
                        String select_id = "";
                        for (int i = 0; i < index; i++) {
                            for (ShopCarListBeen.DataBean.ValidBean.GoodsBeanX goodsBeanX : mList.get(i).getGoods()) {
                                if (goodsBeanX.isIs_select()) {
                                    if (select_id.isEmpty()) {
                                        select_id = goodsBeanX.getId() + "";
                                    } else {
                                        select_id = select_id + "," + goodsBeanX.getId();
                                    }
                                }
                            }
                        }
                        if (select_id.isEmpty()) {
                            Toast.makeText(getActivity(), "请选中结算的商品", Toast.LENGTH_SHORT).show();
                        } else {
                            Log.e("购物车id", " " + select_id);
                            String user_curent_lng = UtilsData.getPreference(getActivity(), "coordinates").getString("coordinates_lng");
                            String user_curent_lat = UtilsData.getPreference(getActivity(), "coordinates").getString("coordinates_lat");
                            mPresenter.confirm(select_id, user_curent_lng, user_curent_lat);
                        }
                    }
                }
            });
            if (mList.size() == 0) {
                rlBottom.setVisibility(View.GONE);
                llCarEmpty.setVisibility(View.VISIBLE);
            } else {
                rlBottom.setVisibility(View.VISIBLE);
                llCarEmpty.setVisibility(View.GONE);
            }
        } else {

        }

    }

    @Override
    public void onUpdateCarNumSuccess(BaseObjectBean bean, int number, int one_position, int position) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            mList.get(one_position).getGoods().get(position).setCart_num(number);
            carWholesaleAdapter.notifyDataSetChanged();
            double total_money = 0;
            for (int i = 0; i < index; i++) {
                for (ShopCarListBeen.DataBean.ValidBean.GoodsBeanX goodsBeanX : mList.get(i).getGoods()) {
                    if (goodsBeanX.isIs_select()) {
                        total_money = Utils.addDouble(total_money, Utils.mul(goodsBeanX.getCart_num(), Double.parseDouble(goodsBeanX.getProductInfo().getPrice())));
                    }
                }

            }
            tvTotalMonry.setText("¥" + total_money);
        } else {
            mList.get(one_position).getGoods().get(position).setCart_num(mList.get(one_position).getGoods().get(position).getCart_num());
            carWholesaleAdapter.notifyDataSetChanged();
            if (bean.getStatus() == Constants.LOGIN_CODE) {
                UtilsData.getPreference(getActivity(), "login").remove("head_url");
                UtilsData.getPreference(getActivity(), "login").remove("nickname");
                UtilsData.getPreference(getActivity(), "login").remove("is_store");
                UtilsData.getPreference(getActivity(), "login").remove("token");
                APP_TOKEN = "";
                Intent intent = new Intent(getActivity(), OneLoginMainActivity.class);
                startActivity(intent);
                return;
            }
            Toast.makeText(getActivity(), bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
        EventBus.getDefault().post(new HomeFlushCarData());

    }

    @Override//删除商品
    public void onRemoveGoodSuccess(BaseObjectBean bean, int one_position, int position, boolean isAll) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            //刷新购物车数据
            EventBus.getDefault().post(new PostCarNumMessage());
            if (mList.get(one_position).getGoods().size() == 1 || isAll) {
                mList.remove(one_position);
                index = index - 1;
                if (mList.size() == 0) {
                    rlBottom.setVisibility(View.GONE);
                    llCarEmpty.setVisibility(View.VISIBLE);
                } else {
                    rlBottom.setVisibility(View.VISIBLE);
                    llCarEmpty.setVisibility(View.GONE);
                }
            } else {
                mList.get(one_position).getGoods().remove(position);
            }
            carWholesaleAdapter.notifyDataSetChanged();
            double total_money = 0;
            for (int i = 0; i < index; i++) {
                for (ShopCarListBeen.DataBean.ValidBean.GoodsBeanX goodsBeanX : mList.get(i).getGoods()) {
                    if (goodsBeanX.isIs_select()) {
                        total_money = Utils.addDouble(total_money, Utils.mul(goodsBeanX.getCart_num(), Double.parseDouble(goodsBeanX.getProductInfo().getPrice())));
                    }
                }

            }
            tvTotalMonry.setText("¥" + total_money);
        } else {
            if (bean.getStatus() == Constants.LOGIN_CODE) {
                UtilsData.getPreference(getActivity(), "login").remove("head_url");
                UtilsData.getPreference(getActivity(), "login").remove("nickname");
                UtilsData.getPreference(getActivity(), "login").remove("is_store");
                UtilsData.getPreference(getActivity(), "login").remove("token");
                APP_TOKEN = "";
                Intent intent = new Intent(getActivity(), OneLoginMainActivity.class);
                startActivity(intent);
                return;
            }
            Toast.makeText(getActivity(), bean.getMsg(), Toast.LENGTH_SHORT).show();
        }

        EventBus.getDefault().post(new HomeFlushCarData());
    }

    @Override
    public void onConfirmSuccess(ConfirmGoodBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            Intent intent = new Intent(getActivity(), XFDConfirmOrderActivity.class);
            intent.putExtra("data", bean.getData());
            startActivity(intent);
        } else if (bean.getStatus() == 2000) {
            Toast.makeText(getActivity(), "此商铺已打烊", Toast.LENGTH_SHORT).show();
        } else {
            if (bean.getStatus() == Constants.LOGIN_CODE) {
                UtilsData.getPreference(getActivity(), "login").remove("head_url");
                UtilsData.getPreference(getActivity(), "login").remove("nickname");
                UtilsData.getPreference(getActivity(), "login").remove("is_store");
                UtilsData.getPreference(getActivity(), "login").remove("token");
                APP_TOKEN = "";
                Intent intent = new Intent(getActivity(), OneLoginMainActivity.class);
                startActivity(intent);
                return;
            }
            Toast.makeText(getActivity(), bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    EditText ettNum;
    View layout;
    @Override
    public void dialog_num(int one_position, int two_position) {

        if (dialog == null) {
            dialog = new Dialog(getActivity(), R.style.ExitDialog);
              layout = View.inflate(getActivity(), R.layout.dialog_update_num, null);
            dialog.setContentView(layout);
            dialog.setCanceledOnTouchOutside(true);
            ettNum = layout.findViewById(R.id.ett_num);

            layout.findViewById(R.id.tvw_dialog_cancel).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
        }
        layout.findViewById(R.id.tvw_dialog_determine).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                if (ettNum.getText().toString().isEmpty()) {
                    if (mList.get(one_position).getGoods().get(two_position).getStore().getIs_self_store().equals("1")) {
                        mPresenter.updateCarNum(mList.get(one_position).getGoods().get(two_position).getId() + "", mList.get(one_position).getGoods().get(two_position).getIs_support(), one_position, two_position);
                    } else {
                        mPresenter.updateCarNum(mList.get(one_position).getGoods().get(two_position).getId() + "", 1, one_position, two_position);

                    }
                } else {
                    if (mList.get(one_position).getGoods().get(two_position).getStore().getIs_self_store().equals("1")) {
                        if (Integer.parseInt(ettNum.getText().toString().trim()) >= mList.get(one_position).getGoods().get(two_position).getIs_support()) {
                            mPresenter.updateCarNum(mList.get(one_position).getGoods().get(two_position).getId() + "", Integer.parseInt(ettNum.getText().toString().trim()), one_position, two_position);
                        } else {
                            mPresenter.updateCarNum(mList.get(one_position).getGoods().get(two_position).getId() + "", mList.get(one_position).getGoods().get(two_position).getIs_support(), one_position, two_position);
                        }
                    } else {
                        mPresenter.updateCarNum(mList.get(one_position).getGoods().get(two_position).getId() + "", Integer.parseInt(ettNum.getText().toString().trim()), one_position, two_position);
                    }
                }
            }
        });
        ettNum.getText().clear();
        dialog.show();


    }

    public static CarMarketPurchaseFragment newInstance(int userUid) {
        Bundle bundle = new Bundle();
//        bundle.putString("item", "UserPostFragment");
        CarMarketPurchaseFragment fragment = new CarMarketPurchaseFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        if (dialog != null) {
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
        }
        mList.clear();
        mList = null;
        super.onDestroy();
    }
}
